package vn.kiemviec.app.utils;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;

public class TrustedRegistryFactory extends SSLSocketFactory {

	private final static String TAG = TrustedRegistryFactory.class.getSimpleName();

	private SSLContext sslContext = SSLContext.getInstance("TLS");

	private TrustedRegistryFactory(KeyStore keyStore) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
		super(keyStore);

		TrustManager tm = new X509TrustManager() {
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			@Override
			public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
			}

			@Override
			public void checkClientTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
			}
		};

		sslContext.init(null, new TrustManager[] {
			tm
		}, null);
	}

	@Override
	public Socket createSocket() throws IOException {
		return sslContext.getSocketFactory().createSocket();
	}

	@Override
	public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
		return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
	}

	public static SchemeRegistry newTrustedSchemeRegistry() {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);

			SSLSocketFactory socketFactory = new TrustedRegistryFactory(trustStore);
			socketFactory.setHostnameVerifier(ALLOW_ALL_HOSTNAME_VERIFIER);

			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			registry.register(new Scheme("https", socketFactory, 443));

			return registry;
		} catch (Exception e) {
//			LogUtils.error(TAG, "create httpclient error.", e);
			throw new RuntimeException();
		}
	}

}
